package cn.tedu.dbinit;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.jdbc.datasource.init.ScriptUtils;

import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import java.sql.SQLException;

@SpringBootApplication
public class DbinitApplication {
    @Autowired
    private DataSource ds;

    public static void main(String[] args) {
        SpringApplication.run(DbinitApplication.class, args);
    }

    @PostConstruct
    public void init() throws SQLException {
        exec("sql/account.sql");
        exec("sql/order.sql");
        exec("sql/seata-server.sql");
        exec("sql/storage.sql");
    }

    private void exec(String sql) throws SQLException {
        /*
        sql = "sql/storage.sql"
        使用 DbinitApplication 类的类加载器，
        得到 DbinitApplication 类所在的根路径，
        拼到 sql 前面
         */
        ClassPathResource cpr =
            new ClassPathResource(
                    sql, DbinitApplication.class.getClassLoader());
        EncodedResource resource = new EncodedResource(cpr);

        ScriptUtils.executeSqlScript(
                ds.getConnection(),
                resource);
        /*
        如果使用 mysql 5.x
        - 四个文件中的 DATETIME(6) 修改成 DATETIME
        - order.sql 中，最后一行
           两个 NOW() 修改成 0
         */
    }

}
